package com.yc.springboot.web;

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Hashtable;

//每次浏览器连接上来，都会创建一个新的TalkServer对象， 坑！！！
@ServerEndpoint(("/talk/{id}"))
@Component
public class TalkServer {



    //存放所有在线用户的集合
    static Hashtable<String,Session> sessions = new Hashtable<>();

    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session){
        //给当前登录用户发送已登录用户
        sessions.values().forEach( s->{
            send(session,new Msg(s.getUserProperties().get("id").toString(),null,s.getUserProperties().get("id").toString(),"上线了"));
        });

        sessions.put(id,session);
        //将id保存到会话
        session.getUserProperties().put("id",id);

        sessions.values().forEach( s->{
            send(s,new Msg(id,null,id,"上线了"));
        });
    }

    @OnClose
    public void onClose(Session session){
        String id = (String)session.getUserProperties().get("id");
        sessions.remove(id);
        sessions.values().forEach( s->{
            send(s,new Msg(null,id,id,"下线了"));
        });
    }

    //接收到用户发送的消息  => 转发
    @OnMessage
    public void onMessage(String message,Session session){
        //群发
        sessions.values().forEach( s -> {
            send(s,new Msg(null,null,(String)session.getUserProperties().get("id"),message));
        });

        //私聊


        //自定义群发
    }

    Gson gson = new Gson();


    /**
     * 给指定客户端发送消息
     * @param session 客户端
     * @param object  发送的消息
     */
    private void send(Session session,Object object){
        String message = gson.toJson(object);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("发送消息错误"+e);
        }
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Msg{
    String onlineUser; //上线用户
    String downlineUser;//下线用户
    String sendUser;//发送消息的用户
    String sendMsg;//发送的消息
}
